// Initialize IndexedDB connection
let db;
const dbRequest = indexedDB.open("XiaohongshuSearchDB", 1);

// DOM elements
const searchInput = document.getElementById("search-input");
const tableBody = document.getElementById("table-body");
const paginationEl = document.getElementById("pagination");
const exportJsonBtn = document.getElementById("export-json");
const exportCsvBtn = document.getElementById("export-csv");
const clearDataBtn = document.getElementById("clear-data");

// Pagination settings
const ITEMS_PER_PAGE = 10;
let currentPage = 1;
let totalPages = 1;
let allData = [];
let filteredData = [];

// Event listeners
searchInput.addEventListener("input", debounce(filterData, 300));
exportJsonBtn.addEventListener("click", exportJSON);
exportCsvBtn.addEventListener("click", exportCSV);
clearDataBtn.addEventListener("click", clearData);

// Database initialization
dbRequest.onupgradeneeded = function(event) {
  db = event.target.result;
  if (!db.objectStoreNames.contains("searchResults")) {
    const store = db.createObjectStore("searchResults", { keyPath: "id", autoIncrement: true });
    store.createIndex("query", "query", { unique: false });
    store.createIndex("timestamp", "timestamp", { unique: false });
  }
};

dbRequest.onsuccess = function(event) {
  db = event.target.result;
  loadAllData();
};

dbRequest.onerror = function(event) {
  console.error("Error opening database:", event.target.error);
  showError("无法打开数据库，请刷新后重试");
};

// Load all data from IndexedDB
function loadAllData() {
  if (!db) return;
  
  const transaction = db.transaction(["searchResults"], "readonly");
  const store = transaction.objectStore("searchResults");
  const index = store.index("timestamp");
  const request = index.openCursor(null, "prev");
  
  allData = [];
  
  request.onsuccess = function(event) {
    const cursor = event.target.result;
    if (cursor) {
      allData.push(cursor.value);
      cursor.continue();
    } else {
      filteredData = [...allData];
      totalPages = Math.ceil(filteredData.length / ITEMS_PER_PAGE);
      renderPagination();
      renderTable();
    }
  };
}

// Filter data by search query
function filterData() {
  const query = searchInput.value.trim().toLowerCase();
  
  if (query === "") {
    filteredData = [...allData];
  } else {
    filteredData = allData.filter(item => 
      item.query.toLowerCase().includes(query)
    );
  }
  
  currentPage = 1;
  totalPages = Math.ceil(filteredData.length / ITEMS_PER_PAGE);
  renderPagination();
  renderTable();
}

// Render the data table
function renderTable() {
  tableBody.innerHTML = "";
  
  // Add styles for the avatar and thumbnail
  const style = document.createElement("style");
  if (!document.getElementById("data-view-styles")) {
    style.id = "data-view-styles";
    style.textContent = `
      .user-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        object-fit: cover;
      }
      .thumbnail {
        width: 60px;
        height: 60px;
        object-fit: cover;
        cursor: pointer;
      }
    `;
    document.head.appendChild(style);
  }
  
  const start = (currentPage - 1) * ITEMS_PER_PAGE;
  const end = Math.min(start + ITEMS_PER_PAGE, filteredData.length);
  const pageData = filteredData.slice(start, end);
  
  if (pageData.length === 0) {
    const row = document.createElement("tr");
    row.innerHTML = `<td colspan="5" style="text-align: center;">没有找到数据</td>`;
    tableBody.appendChild(row);
    return;
  }
  
  pageData.forEach(item => {
    console.log(item, JSON.stringify(item));
    // {"query":"unknown_query","data":{"id":"67d50fbd000000001c002498","query":"unknown_query","user":{"user_id":"645f9dc50000000010029c34","nickname":"鹿仁假","xsec_token":"ABub4mRfGkCW_duqp8IzRDXfwWQDpZ5cIL3Jwb-GWxFiU=","nick_name":"鹿仁假","avatar":"https://sns-avatar-qc.xhscdn.com/avatar/1040g2jo31f0komic665g5p2vjn2k571ki4chetg?imageView2/2/w/80/format/jpg"},"title":"还能不能约了？","image":"http://sns-webpic-qc.xhscdn.com/202504281612/1bfa7b448efcb47c6dea2918279c09ac/1040g2sg31f1o9eep6odg5p2vjn2k571kmbts61g!nc_n_webp_mw_1","image_list":[{"height":1655,"width":3958,"info_list":[{"image_scene":"WB_DFT","url":"http://sns-webpic-qc.xhscdn.com/202504281612/1bfa7b448efcb47c6dea2918279c09ac/1040g2sg31f1o9eep6odg5p2vjn2k571kmbts61g!nc_n_webp_mw_1"},{"image_scene":"WB_PRV","url":"http://sns-webpic-qc.xhscdn.com/202504281612/21672c406178fce06d8ed623aa4fd6c4/1040g2sg31f1o9eep6odg5p2vjn2k571kmbts61g!nc_n_webp_prv_1"}]},{"height":2560,"width":1313,"info_list":[{"image_scene":"WB_DFT","url":"http://sns-webpic-qc.xhscdn.com/202504281612/66208d6f8761bfc27691f9c46fc83bac/1040g2sg31f1o9eep6ocg5p2vjn2k571kk6orl20!nc_n_webp_mw_1"},{"image_scene":"WB_PRV","url":"http://sns-webpic-qc.xhscdn.com/202504281612/f099cd6ef5710eb3a2d45b14c8e503aa/1040g2sg31f1o9eep6ocg5p2vjn2k571kk6orl20!nc_n_webp_prv_1"}]},{"width":1785,"info_list":[{"image_scene":"WB_DFT","url":"http://sns-webpic-qc.xhscdn.com/202504281612/b7290a23025e189fa0df489730c06754/1040g2sg31f1o9eep6od05p2vjn2k571krnkasto!nc_n_webp_mw_1"},{"image_scene":"WB_PRV","url":"http://sns-webpic-qc.xhscdn.com/202504281612/8bc7b4908218e09b4ff1b33db47d379f/1040g2sg31f1o9eep6od05p2vjn2k571krnkasto!nc_n_webp_prv_1"}],"height":3669}],"corner_tag_info":[{"type":"publish_time","text":"03-15"}],"type":"normal","timestamp":"2025-04-28T08:12:11.925Z","url":"https://www.xiaohongshu.com/search_result/?keyword=12123%25E8%2580%2583%25E8%25AF%2595%25E9%25A2%2584%25E7%25BA%25A6%25E5%258F%2597%25E7%2590%2586%25E4%25B8%25AD&source=web_explore_feed&type=51"},"timestamp":"2025-04-28T08:12:11.972Z","url":"https://www.xiaohongshu.com/search_result/?keyword=12123%25E8%2580%2583%25E8%25AF%2595%25E9%25A2%2584%25E7%25BA%25A6%25E5%258F%2597%25E7%2590%2586%25E4%25B8%25AD&source=web_explore_feed&type=51","id":11}'
    
    const row = document.createElement("tr");
    const resultCount = item.data.result?.length || item.data.data?.length || 0;
    const data = item.data || {}
    const date = new Date(item.timestamp).toLocaleString();
    
    row.innerHTML = `
      <td>${data.id}</td>
      <td>${data.query}</td>
      <td>${data.title}</td>
      <td>
        ${data.user && data.user.avatar ? 
          `<img src="${data.user.avatar}" alt="用户头像" class="user-avatar" title="${data.user?.nickname || '用户'}" />` : 
          '无头像'}
      </td>
      <td>
        ${data.image ? 
          `<img src="${data.image}" alt="图片缩略图" class="thumbnail" />` : 
          '无图片'}
      </td>
      <td>${date}</td>
      <td>${resultCount}</td>
      <td> 
        <button class="detail-btn btn" data-id="${item.id}">查看详情</button>
      </td>
    `;
    
    tableBody.appendChild(row);
  });
  
  // Add event listeners to detail buttons
  const detailBtns = document.querySelectorAll(".detail-btn");
  detailBtns.forEach(btn => {
    btn.addEventListener("click", () => {
      const id = parseInt(btn.getAttribute("data-id"));
      const item = filteredData.find(d => d.id === id);
      if (item) {
        showDataDetail(item);
      }
    });
  });
  
  // Add event listeners to thumbnails
  const thumbnails = document.querySelectorAll(".thumbnail");
  thumbnails.forEach(img => {
    img.addEventListener("click", () => {
      showLargeImage(img.src);
    });
  });
}

// Render pagination
function renderPagination() {
  paginationEl.innerHTML = "";
  
  if (totalPages <= 1) return;
  
  // Previous button
  const prevBtn = document.createElement("button");
  prevBtn.innerHTML = "上一页";
  prevBtn.disabled = currentPage === 1;
  prevBtn.addEventListener("click", () => {
    if (currentPage > 1) {
      currentPage--;
      renderTable();
      renderPagination();
    }
  });
  paginationEl.appendChild(prevBtn);
  
  // Page buttons
  let startPage = Math.max(1, currentPage - 2);
  let endPage = Math.min(totalPages, startPage + 4);
  
  if (endPage - startPage < 4) {
    startPage = Math.max(1, endPage - 4);
  }
  
  for (let i = startPage; i <= endPage; i++) {
    const pageBtn = document.createElement("button");
    pageBtn.innerHTML = i;
    pageBtn.classList.toggle("active", i === currentPage);
    
    pageBtn.addEventListener("click", () => {
      currentPage = i;
      renderTable();
      renderPagination();
    });
    
    paginationEl.appendChild(pageBtn);
  }
  
  // Next button
  const nextBtn = document.createElement("button");
  nextBtn.innerHTML = "下一页";
  nextBtn.disabled = currentPage === totalPages;
  nextBtn.addEventListener("click", () => {
    if (currentPage < totalPages) {
      currentPage++;
      renderTable();
      renderPagination();
    }
  });
  paginationEl.appendChild(nextBtn);
}

// Show data detail
function showDataDetail(data) {
  // Create a modal to display detailed information
  const modal = document.createElement("div");
  modal.className = "modal";
  
  const resultCount = data.data.result?.length || data.data.data?.length || 0;
  
  let resultHtml = "";
  // resultData.forEach((item, index) => {
    resultHtml += `
      <div class="result-item">
        <pre>${JSON.stringify(data, null, 2)}</pre>
      </div>
    `;
  // });
  
  modal.innerHTML = `
    <div class="modal-content">
      <span class="close">&times;</span>
      <h2>查询详情: ${data.query}</h2>
      <p>时间: ${new Date(data.timestamp).toLocaleString()}</p>
      <p>结果数: ${resultCount}</p>
      <p>URL: ${data.url || "N/A"}</p>
      <div class="result-details">
        ${resultHtml}
      </div>
    </div>
  `;
  
  document.body.appendChild(modal);
  
  // Add modal styles
  const style = document.createElement("style");
  style.textContent = `
    .modal {
      display: block;
      position: fixed;
      z-index: 1000;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0,0,0,0.4);
    }
    
    .modal-content {
      background-color: white;
      margin: 5% auto;
      padding: 20px;
      border-radius: 8px;
      width: 80%;
      max-width: 800px;
      max-height: 80vh;
      overflow-y: auto;
    }
    
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }
    
    .close:hover {
      color: black;
    }
    
    .result-details {
      margin-top: 20px;
      border-top: 1px solid #ddd;
      padding-top: 20px;
    }
    
    .result-item {
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #eee;
    }
    
    pre {
      background-color: #f8f8f8;
      padding: 10px;
      overflow-x: auto;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  `;
  
  document.head.appendChild(style);
  
  // Close modal when clicking the x
  const closeBtn = modal.querySelector(".close");
  closeBtn.addEventListener("click", () => {
    document.body.removeChild(modal);
  });
  
  // Close modal when clicking outside of it
  window.addEventListener("click", (event) => {
    if (event.target === modal) {
      document.body.removeChild(modal);
    }
  });
}

// Show large image
function showLargeImage(src) {
  const modal = document.createElement("div");
  modal.className = "modal";
  
  modal.innerHTML = `
    <div class="modal-content image-modal">
      <span class="close">&times;</span>
      <img src="${src}" alt="大图" class="large-image">
    </div>
  `;
  
  document.body.appendChild(modal);
  
  // Add modal styles if not already added
  if (!document.getElementById("image-modal-styles")) {
    const style = document.createElement("style");
    style.id = "image-modal-styles";
    style.textContent = `
      .image-modal {
        text-align: center;
      }
      .large-image {
        max-width: 90%;
        max-height: 80vh;
        margin: 0 auto;
      }
    `;
    document.head.appendChild(style);
  }
  
  // Close modal when clicking the x
  const closeBtn = modal.querySelector(".close");
  closeBtn.addEventListener("click", () => {
    document.body.removeChild(modal);
  });
  
  // Close modal when clicking outside of it
  window.addEventListener("click", (event) => {
    if (event.target === modal) {
      document.body.removeChild(modal);
    }
  });
}

// Export all data as JSON
function exportJSON() {
  if (allData.length === 0) {
    alert("没有数据可以导出");
    return;
  }
  
  const json = JSON.stringify(allData, null, 2);
  
  // Create and download file
  const blob = new Blob([json], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `xiaohongshu_search_data_${new Date().toISOString().slice(0,10)}.json`;
  a.click();
  
  URL.revokeObjectURL(url);
}

// Export data as CSV
function exportCSV() {
  if (allData.length === 0) {
    alert("没有数据可以导出");
    return;
  }
  
  let csv = "ID,查询关键词,时间戳,结果数量,URL\n";
  
  allData.forEach(item => {
    const resultCount = item.data.result?.length || item.data.data?.length || 0;
    csv += `${item.id},"${item.query}","${item.title}","${item.user.nickname}","${item.image}","${item.timestamp}",${resultCount},"${item.url || ''}"\n`;
  });
  
  // Create and download file
  const blob = new Blob([csv], { type: "text/csv;charset=utf-8" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `xiaohongshu_search_data_${new Date().toISOString().slice(0,10)}.csv`;
  a.click();
  
  URL.revokeObjectURL(url);
}

// Clear all data
function clearData() {
  if (!db) return;
  
  if (confirm("确定要删除所有已保存的数据吗？此操作不可撤销。")) {
    const transaction = db.transaction(["searchResults"], "readwrite");
    const store = transaction.objectStore("searchResults");
    const request = store.clear();
    
    request.onsuccess = function() {
      alert("数据已清空");
      allData = [];
      filteredData = [];
      totalPages = 1;
      currentPage = 1;
      renderPagination();
      renderTable();
    };
  }
}

// Show error
function showError(message) {
  const errorDiv = document.createElement("div");
  errorDiv.style.color = "red";
  errorDiv.style.padding = "10px";
  errorDiv.textContent = message;
  document.body.insertBefore(errorDiv, document.body.firstChild);
}

// Debounce function for search input
function debounce(func, wait) {
  let timeout;
  return function() {
    clearTimeout(timeout);
    timeout = setTimeout(() => func.apply(this, arguments), wait);
  };
} 